﻿using System;
using System.Collections.Generic;
using System.IO;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.LIB;
using YArchitech.Revit;
using YArchitech.Revit.Electric.Common;
using HYDragCurveJig;

namespace HYRElectric.Equipment
{
	public class SwitchBoxesLayout : EquipmentLayout
	{
		public SwitchBoxesLayout(ExternalCommandData data, DbFamilyObject familyObject, FamilySymbol selectedFamilySymbol, List<BuiltInCategory> lstFilter) : base(data.Application.ActiveUIDocument, data.Application.ActiveUIDocument.Document, familyObject, selectedFamilySymbol, lstFilter)
		{
			this.m_equip = new EquipBoundaryCvs(this.dbFamilyObject);
			this.m_data = data;
		}

		public override bool Layout()
		{
			if (!base.Layout())
			{
				return false;
			}
			this.m_form = new SwitchBoxesLayoutForm();
			this.m_form.Show(WindowHelper.HWndRevit);
			WindowHelper.SendMessageToWndRevit();
			this.m_fiSymbolTag = this.GetSwitchBoxesTagFiSymbol();
			List<JigEdgeInfo> list = null;
			List<JigTextInfo> textInfos = new List<JigTextInfo>();
			for (;;)
			{
				try
				{
					if (list == null)
					{
						list = this.CreateJigCvs(this.m_form.Count);
					}
					XYZ xyz = XYZ.Zero;
					xyz += XYZ.BasisX * AssistFunc.mmToFeet(this.m_form.OffsetX);
					xyz += XYZ.BasisY * AssistFunc.mmToFeet(this.m_form.OffsetY);
					XYZ xyz2 = XYZ.Zero;
					if (DragCurveJigInterface.GetInsertPosition(this.m_data, list, false, textInfos, false, -xyz, ref xyz2))
					{
						xyz2 = new XYZ(xyz2.X, xyz2.Y, 0.0);
						this.CreateEquipFiInstances(xyz2);
						continue;
					}
					this.m_form.InfoChanged = false;
					if (this.m_form.IsKeyboardEsc)
					{
						throw new Exception();
					}
					this.m_form.IsKeyboardEsc = true;
					list = null;
					continue;
				}
				catch (Exception)
				{
				}
				break;
			}
			this.m_form.Close();
			return true;
		}

		private List<JigEdgeInfo> CreateJigCvs(int nCountEquip)
		{
			Transform transformMat = this.GetTransformMat();
			List<JigEdgeInfo> list = new List<JigEdgeInfo>();
			XYZ xyz = XYZ.Zero;
			for (int i = 0; i < nCountEquip; i++)
			{
				Transform transform = Transform.CreateTranslation(xyz);
				transform = transformMat.Multiply(transform);
				list.AddRange(this.m_equip.CreateEquipBoundaryCvs(transform));
				xyz += XYZ.BasisX * this.m_equip.EquipX;
			}
			return list;
		}

		private bool CreateEquipFiInstances(XYZ ptIns)
		{
			if (this.m_form.Count < 1)
			{
				return false;
			}
			double num = 0.004921259842519685;
			double num2 = 1.0;
			IEnumerator<Element> enumerator = new FilteredElementCollector(this.doc.EditFamily(this.m_fiSymbolTag.Family)).OfClass(typeof(TextElement)).ToElements().GetEnumerator();
			{
				if (enumerator.MoveNext())
				{
					TextElementType symbol = ((TextElement)enumerator.Current).Symbol;
					num = symbol.get_Parameter(BuiltInParameter.TEXT_SIZE).AsDouble();
					num2 = symbol.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE).AsDouble();
				}
			}
			Transaction transaction = new Transaction(this.doc, "SwitchBoxesLayout");
			try
			{
				transaction.Start();
				string prefix = this.m_form.Prefix;
				int num3 = this.m_form.StartNum;
				XYZ insPoint = this.GetInsPoint();
				double equipAng = this.GetEquipAng();
				XYZ xyz = XYZ.Zero;
				for (int i = 0; i < this.m_form.Count; i++)
				{
					FamilyInstance familyInstance = YJKRevitTools.LayFamilySymbol(this.doc, xyz, this.familySymbol, this.doc.ActiveView.GenLevel, 0.0);
					if (familyInstance != null)
					{
						Line line = Line.CreateBound(insPoint, insPoint + XYZ.BasisZ * 10.0);
						ElementTransformUtils.RotateElement(this.doc, familyInstance.Id, line, equipAng);
						XYZ xyz2 = XYZ.BasisX * AssistFunc.mmToFeet(this.m_form.OffsetX);
						xyz2 += XYZ.BasisY * AssistFunc.mmToFeet(this.m_form.OffsetY);
						ElementTransformUtils.MoveElement(this.doc, familyInstance.Id, ptIns - insPoint + xyz2);
						base.SetParametersValue(familyInstance, this.dbFamilyObject.Size);
						if (this.m_form.IsDim)
						{
							string text = prefix + num3.ToString();
							familyInstance.GetParameter("配电盘名称").Set(text);
							if (this.m_fiSymbolTag != null)
							{
								Transform transform = familyInstance.GetTransform();
								XYZ xyz3 = transform.Origin;
								xyz3 += transform.BasisX * this.m_equip.EquipX * 0.5;
								IndependentTag independentTag = this.doc.Create.NewTag(this.doc.ActiveView, familyInstance, false, 0, 0, xyz3);
								independentTag.ChangeTypeId(this.m_fiSymbolTag.Id);
								XYZ tagHeadPosition = xyz3 - (double)StringTools.GetStringByteLength(independentTag.TagText) * num * num2 * 0.5 * ((double)YJKRevitTools.GetViewPlanScale(this.doc) / 100.0) * transform.BasisX;
								independentTag.TagHeadPosition = tagHeadPosition;
							}
						}
					}
					xyz += XYZ.BasisX * this.m_equip.EquipX;
					if (this.m_form.SortType == SwitchBoxesLayoutForm.ELabelSortType.eSortAsc)
					{
						num3++;
					}
					else
					{
						num3--;
					}
				}
				transaction.Commit();
			}
			catch (Exception)
			{
				transaction.RollBack();
				return false;
			}
			return true;
		}

		private FamilySymbol GetSwitchBoxesTagFiSymbol()
		{
			string familyFile = this.GetFamilyFile();
            return this.GetFamilySymbol(familyFile, BuiltInCategory.OST_ElectricalEquipmentTags);
		}

		private string GetFamilyFile()
		{
			return Path.Combine(Product.FamilyLocation, RevitVersion.GetVersionNumber(this.doc), "ElectricMark", "配电柜编号.rfa");
		}

		private FamilySymbol GetFamilySymbol(string familyFile, BuiltInCategory builtInCategory)
		{
			FamilySymbol result = null;
			Family family = null;
			if (this.doc == null || !File.Exists(familyFile))
			{
				return null;
			}
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(familyFile);
			Transaction transaction = null;
			try
			{
				foreach (Element element in YJKElementFilter.GetElementByCategory(this.doc, typeof(FamilySymbol), builtInCategory))
				{
					FamilySymbol familySymbol = element as FamilySymbol;
					if (familySymbol.Family.Name == fileNameWithoutExtension)
					{
						return familySymbol;
					}
				}
				transaction = new Transaction(this.doc, "LoadFamily");
				transaction.Start();
				this.doc.LoadFamily(familyFile, out family);
				transaction.Commit();
			}
			catch (Exception)
			{
			}
			finally
			{
                if (transaction != null && transaction.GetStatus() != TransactionStatus.Committed)
				{
					transaction.RollBack();
				}
			}
			if (family != null)
			{
				using (List<FamilySymbol>.Enumerator enumerator2 = family.GetSymbols().GetEnumerator())
				{
					if (enumerator2.MoveNext())
					{
						result = enumerator2.Current;
					}
				}
			}
			return result;
		}

		private Transform GetTransformMat()
		{
			Transform transform = Transform.Identity;
			if (this.m_form != null)
			{
				XYZ insPoint = this.GetInsPoint();
				transform.Origin = -insPoint;
				double num = (double)this.m_form.PlanAng * Math.PI * 0.5;
				Transform transform2 = Transform.CreateRotationAtPoint(XYZ.BasisZ, num, insPoint);
				transform = transform.Multiply(transform2);
			}
			return transform;
		}

		private double GetEquipAng()
		{
			return (double)this.m_form.PlanAng * Math.PI * 0.5;
		}

		private XYZ GetInsPoint()
		{
			XYZ xyz = XYZ.Zero;
			if (this.m_form != null && this.m_equip != null)
			{
				switch (this.m_form.InsPos)
				{
				case SwitchBoxesLayoutForm.EInsPos.eInsPosLeftUp:
					xyz += XYZ.BasisY * (this.m_equip.EquipY * 0.5);
					break;
				case SwitchBoxesLayoutForm.EInsPos.eInsPosLeftDown:
					xyz -= XYZ.BasisY * (this.m_equip.EquipY * 0.5);
					break;
				case SwitchBoxesLayoutForm.EInsPos.eInsPosRightDown:
					xyz += XYZ.BasisX * (this.m_equip.EquipX * (double)this.m_form.Count);
					xyz -= XYZ.BasisY * (this.m_equip.EquipY * 0.5);
					break;
				case SwitchBoxesLayoutForm.EInsPos.eInsPosRightMid:
					xyz += XYZ.BasisX * (this.m_equip.EquipX * (double)this.m_form.Count);
					break;
				case SwitchBoxesLayoutForm.EInsPos.eInsPosRightUp:
					xyz += XYZ.BasisX * (this.m_equip.EquipX * (double)this.m_form.Count);
					xyz += XYZ.BasisY * (this.m_equip.EquipY * 0.5);
					break;
				}
			}
			return xyz;
		}

		private SwitchBoxesLayoutForm m_form;

		private EquipBoundaryCvs m_equip;

		private FamilySymbol m_fiSymbolTag;

		private new ExternalCommandData m_data;

		public static string m_strKeyX = "宽度";

		public static string m_strKeyY = "进深";

		public static string m_strKeyZ = "高度";
	}
}
